package com.lee.customize;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CustomizeSessionContainer {

    public static final String DEFAULT_SESSION_ID_NAME = "JSESSIONID";
    private static final Map<String, CustomizeSession> sessionMap = new ConcurrentHashMap<>();

    public static CustomizeSession getSession(String sessionId, HttpServletResponse response) {
        return getSession(sessionId, true, response);
    }

    public static CustomizeSession getSession(String sessionId, boolean create, HttpServletResponse response) {
        if (sessionId == null) {
            sessionId = "";
        }

        CustomizeSession session = sessionMap.get(sessionId);
        if (session != null) {
            session.setIsNew(false);
            return session;
        }

        if (create) {
            session = new CustomizeSession(sessionId);
            sessionMap.put(session.getId(), session);
            response.addCookie(new Cookie(CustomizeSessionContainer.DEFAULT_SESSION_ID_NAME,
                    session.getId()));
        }

        return session;
    }

}
